package it.ipermemory.utilities;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import it.ipermemory.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

/**
 * Allows you to create a card to share on social networking sites with the
 * score in a game round. The processing is done in a thread.
 * 
 * @author Gianluca Carlesso (gianluca.carlesso@gmail.com)
 * @version 1.0
 * 
 */
public class CreateScoreImage extends Thread {
	/**
	 * A string that identifies the location where you saved the processed image
	 */
	public static final String PATH_KEY = "path";

	/** String that communicates the presence or absence of errors */
	public static final String ERROR_KEY = "error";

	/** User's score */
	private int score;

	/** Context of application */
	private Context context;

	/**
	 * The handler is used to communicate to the ui thread that the development
	 * has been completed
	 */
	private Handler callback;

	/**
	 * Object constructor
	 * 
	 * @param context
	 *            of application
	 * @param handler
	 *            for the callback to the ui thread
	 * @param score
	 *            user's score
	 */
	public CreateScoreImage(Context context, Handler handler, int score) {
		this.context = context;
		this.score = score;
		this.callback = handler;
	}

	/**
	 * Method for starting the thread to perform the processing required
	 */
	@SuppressLint("WorldReadableFiles")
	@SuppressWarnings("deprecation")
	public void run() {
		Resources res = context.getResources();

		// Recovering the image of the background and initializing a Bitmap
		Options options = new BitmapFactory.Options();
		options.inScaled = false;
		options.inDither = false;
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;

		Bitmap background = BitmapFactory.decodeResource(
				context.getResources(), R.drawable.card_share, options).copy(
				Bitmap.Config.ARGB_8888, true);

		// Prepare an image to share, initializing a canvas and adding the
		// necessary elements: label and score
		Canvas canvas = new Canvas(background);
		Typeface font = Typeface.createFromAsset(context.getResources()
				.getAssets(), "fonts/wayoshi.ttf");
		font = Typeface.create(font, Typeface.NORMAL);

		// Text of label score
		Paint paint = new Paint();
		paint.setTypeface(font);
		paint.setAntiAlias(true);
		paint.setColor(Color.rgb(0, 0, 255));
		paint.setStyle(Style.FILL);

		paint.setTextSize(50);
		canvas.drawText(res.getString(R.string.score_label), (background
				.getWidth() - paint.measureText(res
				.getString(R.string.score_label))) / 2,
				background.getHeight() - 135, paint);

		// Text of score
		paint.setColor(Color.rgb(0, 0, 153));

		paint.setTextSize(100);
		canvas.drawText(Integer.toString(score), (background.getWidth() - paint
				.measureText(Integer.toString(score))) / 2, background
				.getHeight() - 30, paint);

		// Store the image in the smartphone memory
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		background.compress(Bitmap.CompressFormat.PNG, 100, bytes);

		File f = null;
		FileOutputStream fo = null;

		String state = Environment.getExternalStorageState();
		String path = null;
		try {

			if (Environment.MEDIA_MOUNTED.equals(state)) {
				// We can read and write the media in external storage
				path = Environment.getExternalStorageDirectory()
						+ File.separator + Environment.DIRECTORY_PICTURES
						+ File.separator + res.getString(R.string.app_name)
						+ ".png";

				f = new File(path);
				f.createNewFile();
				fo = new FileOutputStream(f);

				path = f.getPath();
			} else {
				// No sd card, save image into internal memory
				path = res.getString(R.string.app_name) + ".png";
				fo = context.openFileOutput(path, Context.MODE_WORLD_READABLE);
				path = context.getFilesDir() + File.separator + path;
			}

			fo.write(bytes.toByteArray());
			fo.close();
		} catch (IOException e) {
			// Message error for ui thread
			Message msg = callback.obtainMessage();
			Bundle bundle = new Bundle();
			bundle.putString(ERROR_KEY, Integer.toString(1));
			msg.setData(bundle);
			callback.sendMessage(msg);
		}

		// Scan the media for the image to appear in the App Gallery
		MediaScannerConnection.scanFile(context, new String[] { path },
				new String[] { "image/png" },
				new MediaScannerConnection.OnScanCompletedListener() {
					public void onScanCompleted(String path, Uri uri) {
					}
				});

		// Set the message for ui thread and callback
		Message msg = callback.obtainMessage();
		Bundle bundle = new Bundle();
		bundle.putString(PATH_KEY, path);
		msg.setData(bundle);
		callback.sendMessage(msg);

	}
}
